package com.webtest.jsptest;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/24 15:31
 */
public class ForwardServlet extends HttpServlet {
    private static final long serialVersionUID = -6280289082783975704L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("forward servlet doGet");

        req.setAttribute("name", "abcd");
        System.out.println("forward servlet: " + req.getAttribute("name"));

        // 请求的转发
        // 1. 调用HttpServletRequest的getRequestDispatcher()方法获取RequestDispatcher对象
        // 调用getRequestDispatcher()需要传入转发的地址
        // 2. 调用HttpServletRequest的forward（request, response）进行请求的转发。

        String path = "testServlet";
        RequestDispatcher dispatcher = req.getRequestDispatcher("/" + path);
        dispatcher.forward(req, resp);
    }
}
